<%--
  Created by IntelliJ IDEA.
  User: jimmy
  Date: 2017/7/9
  Time: 11:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"";
    pageContext.setAttribute("basePath",path);
%>
<html>
<head>
    <title>商品管理</title>
</head>
<body>
    <div class="panel-body" style="padding-bottom:0px;">
        <%--<div class="panel panel-default">--%>
            <%--<div class="panel-heading">查询条件</div>--%>
            <%--<div class="panel-body">--%>
                <%--<form id="formSearch" class="form-horizontal">--%>
                    <%--<div class="form-group" style="margin-top:15px">--%>
                        <%--<label class="control-label col-sm-1" for="txt_search_departmentname">商品名称</label>--%>
                        <%--<div class="col-sm-3">--%>
                            <%--<input type="text" class="form-control" id="txt_search_departmentname">--%>
                        <%--</div>--%>
                        <%--<div class="col-sm-4" style="text-align:left;">--%>
                            <%--<button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>--%>
                        <%--</div>--%>
                    <%--</div>--%>
                <%--</form>--%>
            <%--</div>--%>
        <%--</div>--%>

        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
        </div>
        <table id="tb_departments"></table>
    </div>

    <%--模态框--%>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 1200px;height: 1000px;overflow:auto;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">商品添加</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="prodName" class="col-sm-1 control-label">商品名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="prodName" placeholder="商品名称">
                                <input type="hidden" id="prodId">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="prodDesc" class="col-sm-1 control-label">商品描述</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="prodDesc" placeholder="商品描述">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="productType" class="col-sm-1 control-label">商品价格</label>
                            <div class="col-sm-4">
                                <select id="productType" class="selectbox form-control">
                                    <option value="1">进口食品</option>
                                    <option value="2">日化用品</option>
                                    <option value="3">母婴专用</option>
                                    <option value="4">健康养生</option>
                                </select>
                            </div>
                            <label for="isMain" class="col-sm-2 control-label">主页显示</label>
                            <div id="isMain" class="col-sm-4">
                                <div class="radio2 radio-check radio-inline">
                                    <input type="radio" id="radio1" name="radio2" value="1" checked="">
                                    <label for="radio1">
                                        是
                                    </label>
                                </div>
                                <div class="radio2 radio-check radio-success radio-inline">
                                    <input type="radio" id="radio2" name="radio2" value="2" checked="true">
                                    <label for="radio2">
                                        否
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="productPrice" class="col-sm-1 control-label">商品价格</label>
                            <div class="col-sm-4">
                                <input type="number" class="form-control" id="productPrice" placeholder="商品价格">
                            </div>
                            <label for="productDiscountPrice" class="col-sm-2 control-label">会员价格</label>
                            <div class="col-sm-4">
                                <input type="number" class="form-control" id="productDiscountPrice" placeholder="会员价格">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="productMinPrice" class="col-sm-1 control-label">商品进价</label>
                            <div class="col-sm-4">
                                <input type="number" class="form-control" id="productMinPrice" placeholder="商品进价">
                            </div>
                            <label for="productSendFee" class="col-sm-2 control-label">商品运费</label>
                            <div class="col-sm-4">
                                <input type="number" class="form-control" id="productSendFee" placeholder="商品运费">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="prodspec" class="col-sm-1 control-label">商品规格</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="prodspec" placeholder="商品规格">
                            </div>
                            <label for="prodSton" class="col-sm-2 control-label">商品库存</label>
                            <div class="col-sm-4">
                                <input type="number" class="form-control" id="prodSton" placeholder="商品库存">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="mainPic" class="col-sm-1 control-label">首页图片</label>
                            <div class="col-sm-10">
                                <input id="mainPic" name="file" type="file" multiple>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="fileUpload" class="col-sm-1 control-label">商品图片</label>
                            <div class="col-sm-10">
                                <input id="fileUpload" name="file" type="file" multiple>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="contents" class="col-sm-1 control-label">商品详情</label>
                            <div class="col-sm-10">
                                <textarea name="text" class="summernote" id="contents" title="Contents"></textarea>
                            </div>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="submit" type="button" class="btn btn-primary">提交更改</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>


<script>
    $(function () {
        var pics = new Array();
        var mainPic = new Array();
        //1.初始化Table
        var oTable = new TableInit();
        oTable.Init();

        //2.初始化Button的点击事件
        var oButtonInit = new ButtonInit();
        oButtonInit.Init();

        $('#submit').click(function (e) {
            var detail = $('.summernote').val();
            var param = {
                prodId : $('#prodId').val(),
                prodName: $('#prodName').val(),
                prodDesc: $('#prodDesc').val(),
                prodDisPrice: Math.round($('#productDiscountPrice').val() * 100),
                prodPrice: Math.round($('#productPrice').val() * 100),
                prodMinPrice: Math.round($('#productMinPrice').val() * 100),
                prodSendFee:Math.round($('#productSendFee').val() * 100),
                pics:pics,
                mainPic:mainPic,
                prodDetail:detail,
                prodSpec:$('#prodspec').val(),
                prodSton:$('#prodSton').val(),
                prodType:$('#productType option:selected').val(),
                prodMain:$("input[name='radio2']:checked").val()
            };

            $.get('${basePath}/insProd',{'jsonstr':JSON.stringify(param)},function (data) {
                $('#myModal').modal('hide');
                $('#tb_departments').bootstrapTable('refresh',{silent: true});
            });
        });

        $('#fileUpload').fileinput({//初始化上传文件框
            showUpload : false,
            showRemove : false,
            uploadAsync: true,
            uploadLabel: "上传",//设置上传按钮的汉字
            uploadClass: "btn btn-primary",//设置上传按钮样式
            showCaption: false,//是否显示标题
            language: "zh",//配置语言
            uploadUrl: "${basePath}/fileUpload",
            maxFileSize : 0,
            maxFileCount: 4,/*允许最大上传数，可以多个，当前设置单个*/
            enctype: 'multipart/form-data',
            //allowedPreviewTypes : [ 'image' ], //allowedFileTypes: ['image', 'video', 'flash'],
            allowedFileExtensions : ["jpg", "png","gif"],/*上传文件格式*/
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            dropZoneTitle: "请通过拖拽图片文件放到这里",
            dropZoneClickTitle: "或者点击此区域添加图片",
            //uploadExtraData: {"id": id},//这个是外带数据
            showBrowse: false,
            browseOnZoneClick: true,
            slugCallback : function(filename) {
                return filename.replace('(', '_').replace(']', '_');
            }
        }).on("filebatchselected", function(event, files) {
            $(this).fileinput("upload");
        }).on("fileuploaded", function(event, data) {
                if(data.response)
                {
                    var p = {
                        pic:data.response.filenames[0]
                    }
                    pics.push(p);
                }
            });

        $('#mainPic').fileinput({//初始化上传文件框
            showUpload : false,
            showRemove : false,
            uploadAsync: true,
            uploadLabel: "上传",//设置上传按钮的汉字
            uploadClass: "btn btn-primary",//设置上传按钮样式
            showCaption: false,//是否显示标题
            language: "zh",//配置语言
            uploadUrl: "${basePath}/fileUpload",
            maxFileSize : 0,
            maxFileCount: 1,/*允许最大上传数，可以多个，当前设置单个*/
            enctype: 'multipart/form-data',
            //allowedPreviewTypes : [ 'image' ], //allowedFileTypes: ['image', 'video', 'flash'],
            allowedFileExtensions : ["jpg", "png","gif"],/*上传文件格式*/
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
            dropZoneTitle: "请通过拖拽图片文件放到这里",
            dropZoneClickTitle: "或者点击此区域添加图片",
            //uploadExtraData: {"id": id},//这个是外带数据
            showBrowse: false,
            browseOnZoneClick: true,
            slugCallback : function(filename) {
                return filename.replace('(', '_').replace(']', '_');
            }
        }).on("filebatchselected", function(event, files) {
            $(this).fileinput("upload");
        }).on("fileuploaded", function(event, data) {
            if(data.response)
            {
                var p = {
                    pic:data.response.filenames[0]
                }
                mainPic.push(p);
            }
        });

        $('.summernote').summernote({
            height: 400,
            lang:'zh-CN',
            // 重写图片上传
            callbacks: {
                onImageUpload: function(files, editor, $editable) {
                    sendFile(files[0],editor,$editable);
                }
            }
        });
    });

    function sendFile(file, editor, $editable) {
        var filename = false;
        try{
            filename = file['name'];
        } catch(e){
            filename = false;
        }
        if(!filename){
            $(".note-alarm").remove();
        }

        //以上防止在图片在编辑器内拖拽引发第二次上传导致的提示错误

        var p = {"scope":"jimmyzhang","deadline":new Date('2099-12-31').getTime()}
        var token = genUpToken('KlXGGDOZY3Zn948ma2zUTvXWjQE9ARGFi-4zwz6l','psYM4olvoZ9n5ACUcv0vuhvioaVY5A9hDvq3F7NC',p);
        Qiniu_upload(filename,file,token);
    }


    function prodEdit() {
        var a = $('#tb_departments').bootstrapTable('getSelections');
        if(a.length > 1 || a.length == 0){
            alert("请选择一条数据");
            return;
        }
        console.log(a[0].productId);
        $('myModalLabel').val('商品修改');
        $('#prodId').val(a[0].productId);
        $('#prodName').val(a[0].productName);
        $('#prodDesc').val(a[0].productDesc);
        $('#iconUrl').val(a[0].productIcon);
        $('#productDiscountPrice').val(a[0].productDiscountPrice/100);
        $('#productPrice').val(a[0].productPrice/100);
        $('#productMinPrice').val(a[0].productMinPrice/100);
        $('#myModal').modal('show');
    }

    function prodDel() {
        var a = $('#tb_departments').bootstrapTable('getSelections');
        var ids = [];
        for(var i = 0;i< a.length;i++){
            ids[i] = a[i].productId;
        }
        $.get('${basePath}/delProds',{'ids':ids.join(',')},function (data) {
            if(data.code == "0"){
                alert("删除成功");
                $('#tb_departments').bootstrapTable('refresh',{silent: true});
            }
        })
    }

    //普通上传
    var Qiniu_upload = function(filename,f,token) {
        var Qiniu_UploadUrl = "http://up.qiniu.com";
        var token = token;
        var key = filename;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', Qiniu_UploadUrl, true);
        var formData, startDate;
        formData = new FormData();
        if (key !== null && key !== undefined) formData.append('key', key);
        formData.append('token', token);
        formData.append('file', f);
        xhr.onreadystatechange = function(response) {
            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                var blkRet = JSON.parse(xhr.responseText);
                console && console.log(blkRet);
                $(".summernote").summernote('insertImage', 'http://image.bearworker.com/'+filename, filename);
            } else if (xhr.status != 200 && xhr.responseText) {

            }
        };
        xhr.send(formData);
    };

    var genUpToken = function(accessKey, secretKey, putPolicy) {

        //SETP 2
        var put_policy = JSON.stringify(putPolicy);
        console && console.log("put_policy = ", put_policy);

        //SETP 3
        var encoded = base64encode(utf16to8(put_policy));
        console && console.log("encoded = ", encoded);

        //SETP 4
        var hash = CryptoJS.HmacSHA1(encoded, secretKey);
        var encoded_signed = hash.toString(CryptoJS.enc.Base64);
        console && console.log("encoded_signed=", encoded_signed)

        //SETP 5
        var upload_token = accessKey + ":" + safe64(encoded_signed) + ":" + encoded;
        console && console.log("upload_token=", upload_token)
        return upload_token;
    };

    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#tb_departments').bootstrapTable({
                url: '${basePath}/getAllProd',         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: false,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                queryParams: oTableInit.queryParams,//传递参数（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber:1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: true,
                showColumns: true,                  //是否显示所有的列
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
//                height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "productId",                     //每一行的唯一标识，一般为主键列
                showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: true,                   //是否显示父子表
                columns: [{
                    checkbox: true
                }, {
                    field: 'productName',
                    width: '20%',
                    title: '商品名称'
                }, {
                    field: 'productDesc',
                    width: '25%',
                    title: '商品描述'
                }, {
                    field: 'productIcon',
                    width: '15%',
                    title: '商品图标',
                    formatter : function (value, row, index){
                        return '<img width="15%" src="'+value+'" />';
                    }
                }, {
                    field: 'productDiscountPrice',
                    title: '会员价格',
                    formatter : function (value, row, index){
                        return value/100+'元';
                    }
                }, {
                    field: 'productPrice',
                    title: '商品价格',
                    formatter : function (value, row, index){
                        return value/100+'元';
                    }
                },{
                    field: 'productMinPrice',
                    title: '商品进价',
                    formatter : function (value, row, index){
                        return value/100+'元';
                    }
                },{
                    field: 'createTime',
                    title: '创建时间'
                }],
                //注册加载子表的事件。注意下这里的三个参数！
                onExpandRow: function (index, row, $detail) {
                    oTableInit.InitSubTable(index, row, $detail);
                }
            });
        };

        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                limit: params.limit,   //页面大小
                offset: params.offset
            };
            return temp;
        };

        //初始化子表格(无线循环)
        oTableInit.InitSubTable = function (index, row, $detail) {
            var prodId = row.productId;
            var cur_table = $detail.html('<table></table>').find('table');
            $(cur_table).bootstrapTable({
                url: '${basePath}/getProdDet',
                method: 'get',
                sidePagination: "server",
                queryParams: { prodId: prodId },
                ajaxOptions: { prodId: prodId },
                clickToSelect: true,
                detailView: false,//父子表
                uniqueId: "detailId",
                pageSize: 10,
                pageList: [10, 25],
                columns: [{
                    checkbox: true
                }, {
                    field: 'type',
                    title: '类型',
                    formatter : function (value, row, index){
                        switch (value){
                            case "spec":
                                return "规格";
                                break;
                            case "dpic":
                                return "轮播图";
                                break;
                            case "desc":
                                return "描述";
                                break;
                            case "ston":
                                return "库存";
                                break;
                            case "sendfee":
                                return "运费";
                                break;
                            default:
                                return "-";
                                break;
                        }
                    }
                }, {
                    field: 'value',
                    title: '值',
                    formatter : function (value, row, index){
                        switch (row.type){
                            case "spec":
                                return value;
                                break;
                            case "dpic":
                                return "<img width='18%' src='"+value+"' />";
                                break;
                            case "desc":
                                return value;
                                break;
                            case "ston":
                                return value;
                                break;
                            case "sendfee":
                                return value/100;
                                break;
                            default:
                                return "-";
                                break;
                        }
                    }
                }]
            });
        };

        return oTableInit;
    };


    var ButtonInit = function () {
        var oInit = new Object();
        var postdata = {};

        oInit.Init = function () {
            //初始化页面上面的按钮事件
            $('#btn_add').click(function () {
                $('myModalLabel').val('商品添加');
                $('#prodId').val('');
                $('#prodName').val('');
                $('#prodDesc').val('');
                $('#iconUrl').val('');
                $('#productDiscountPrice').val('');
                $('#productPrice').val('');
                $('#productMinPrice').val('');
                $('#myModal').modal('show');
            });
            
            $('#btn_edit').click(function () {
                prodEdit();
            });

            $('#btn_delete').click(function () {
                prodDel();
            });
        };

        return oInit;
    };

    /*
     * Interfaces:
     * b64 = base64encode(data);
     * data = base64decode(b64);
     */
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

    function base64encode(str) {
        var out, i, len;
        var c1, c2, c3;
        len = str.length;
        i = 0;
        out = "";
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += base64EncodeChars.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += base64EncodeChars.charAt(c1 >> 2);
            out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            out += base64EncodeChars.charAt(c3 & 0x3F);
        }
        return out;
    }

    var safe64 = function(base64) {
        base64 = base64.replace(/\+/g, "-");
        base64 = base64.replace(/\//g, "_");
        return base64;
    };

    function utf16to8(str) {
        var out, i, len, c;
        out = "";
        len = str.length;
        for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                out += str.charAt(i);
            } else if (c > 0x07FF) {
                out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
                out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
        }
        return out;
    }

    function _addImgFileListener(obj, fun)
    {
        $(obj).change(function ()
        {
            try
            {
                var file = this.files[0];
                var reader = new FileReader();
                reader.onload = function ()
                {
                    var img = new Image();
                    img.src = reader.result;
                    img.onload = function ()
                    {
                        var w = img.width, h = img.height;
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        $(canvas).attr({
                            width: w,
                            height: h
                        });
                        ctx.drawImage(img, 0, 0, w, h);
                        var base64 = canvas.toDataURL('image/jpeg', 0.5);
                        var result = {
                            url: window.URL.createObjectURL(file),
                            base64: base64,
                            clearBase64: base64.substr(base64.indexOf(',') + 1),
                            suffix: base64.substring(base64.indexOf('/') + 1, base64.indexOf(';')),
                        };
                        fun(result);
                    }
                }
                reader.readAsDataURL(this.files[0]);
            } catch (e)
            {
                alert(e);
            }
        });
    }
</script>
</body>
</html>
